package com.wan.data.mysql.orm.convert;

import cn.hutool.core.lang.Singleton;
import com.sun.istack.internal.NotNull;
import com.wan.data.mysql.exception.DBInitializeException;
import com.wan.data.mysql.orm.meta.ColumnMeta;
import com.wan.data.mysql.util.DbColumnType;
import com.wan.core.strategy.StrategyPool;

public interface Converter {

    default String dbType(long len,int pointLen){
        return getDbType().format(len,pointLen);
    }
    /**
     * 字段类型定义，例如：varchar(255)
     */
    DbColumnType getDbType();

    /**
     * 从数据库中获取指定类型的value
     */
    Object dbToEntity(ColumnMeta columnMeta,@NotNull Object value) throws Exception;
    /**
     * 字段写入到数据库中的value
     */
    Object entityToDb(ColumnMeta columnMeta,@NotNull Object value) throws Exception;

    /**
     * 检查字段
     */
    void tryCheck(ColumnMeta columnMeta) throws DBInitializeException;

    static Converter get(ColumnMeta columnMeta){
        Class<? extends Converter> converter = columnMeta.getConverter();
        Converter converterInstance;
        if(AutoConverter.isAuto(converter)){
            converterInstance = StrategyPool.getStrategy(AutoConverter.class, columnMeta.getFieldType());
        }else{
            converterInstance = Singleton.get(converter);
        }
        if(converterInstance == null){
            throw new DBInitializeException("找不到该类型字段的转换器, " + columnMeta.getFieldType() + " ->> ??");
        }
        return converterInstance;
    }







}
